/**
 * 数据库事务操作封装
 * 
 * @author 迟胜强
 * @date 2018-9-17
 */
package aorey.database;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import aorey.database.config.DataConfigTransactionSQL;

public class DataBaseTransaction extends DataBaseFactory 
{
	
	public DataBaseTransactionReturnStruct transaction(List<DataConfigTransactionSQL> sqls,HttpServletRequest request)
	{
		DataBaseTransactionReturnStruct dataBaseTransactionReturnStruct = new DataBaseTransactionReturnStruct();
		DataTag dataTag = new DataTag(request);
		JSONArray resultData = new JSONArray();
		int size = sqls.size();		
		int sqlReturn;
		String rs;
		try
        {
            this._conn.setAutoCommit(false);
            this._stat = this._conn.createStatement();
            for(int i=0;i<size;i++)
            {
            	System.out.println(dataTag.tagReplace(sqls.get(i).sql));
            	if (null != sqls.get(i).to)
            	{
            		this._rs = this._stat.executeQuery(dataTag.tagReplace(sqls.get(i).sql));
            		this._rsmd = this._rs.getMetaData();
                    int L = this._rsmd.getColumnCount();
//                    System.out.println("len:"+L);
            		ArrayList<String> field = new ArrayList<>();
            		for (int j = 1; j <= L; j++)
                    {
                        field.add(this._rsmd.getColumnLabel(j));
                    }
                    int field_size = field.size();
                    this.fieldList = field;
                    while (this._rs.next())
                    {
                        JSONObject dataField = new JSONObject();
                        for (int j = 0; j < field_size; j++)
                        {
                            dataField.put(field.get(j), this._rs.getString(field.get(j)));
                        }
                        resultData.add(dataField);
                    }
                    dataBaseTransactionReturnStruct.dataCache.put(sqls.get(i).to, resultData.toJSONString());
                    System.out.println("SQL Result:"+resultData.toJSONString());
//                    this._rs.close();
//                    this._stat.close();		
				}
            	else
            	{
            		if (!sqls.get(i).from.equals("")) {
						JSONArray jsonArray = JSONArray.parseArray(dataBaseTransactionReturnStruct.dataCache.get(sqls.get(i).from));
						JSONObject jsonObject;
						int jsonSize = jsonArray.size();
						for(int j= 0 ;j<jsonSize;j++)
						{
							jsonObject = JSONObject.parseObject(jsonArray.getString(j));
							this._stat.executeUpdate(dataTag.dataReplace(sqls.get(i).sql,jsonObject));
							System.out.println("EXE-SQL:"+dataTag.dataReplace(sqls.get(i).sql,jsonObject ));
						}
					}
//            		System.out.println(dataBaseTransactionReturnStruct.dataCache.get(sqls.get(i).from));
            		// 执行普通操作
//            		System.out.println("SQL:"+sqls.get(i).sql);
            	}
            }
            this._conn.commit();
            this._stat.close();
            this._stat = null;
        } catch (Exception e)
        {
        	dataBaseTransactionReturnStruct.result = false;
        	dataBaseTransactionReturnStruct.error = e.getMessage();
        	System.out.println("数据错误!");
        	try {
				this._conn.rollback();
				System.out.println("回滚成功!");
			} catch (SQLException e1) {
				dataBaseTransactionReturnStruct.error = e1.getMessage();
				System.out.println("回滚失败!");
			}
        }
		return dataBaseTransactionReturnStruct;
	}
}
